import * as crypto from 'crypto';

function objKeySort(obj: any) {
    let newKey: any = Object.keys(obj).sort();
    let newObj: any = {};
    for (let i = 0; i < newKey.length; i++) {
        if (obj[newKey[i]] instanceof Object) {
            newObj[newKey[i]] = objKeySort(obj[newKey[i]]);
        } else {
            newObj[newKey[i]] = obj[newKey[i]];
        }
    }
    return newObj;
}

function sign(json: any, privateKey: string): string {
    let sorted = objKeySort(json);
    let data = JSON.stringify(sorted);
    let sign = crypto.createSign('RSA-SHA256');
    sign.write(data);
    sign.end();
    let result = sign.sign(privateKey, 'base64');
    return result;
}

const json = {
    "app_id": "D7F827D5-3EBD-4309-ABD8-9EB7849465D1",
    "data": {},
    "timestamp": "1664524209"
};

const privateKey = `MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKzjXPNctAti+z87La3QjCcAmV2JI7sxSEzUYMclmDgLPbHNTMfql7klqe8FLhcx7uNcTS+SUXmndjNRlH/q1lGyqwO1zePHFuHIVf9wecUXANKRLcG+n+RdCB0eNzwJYqg3L1uPY1wzsLwUxs8EVGXREZIJ82eDPHIb5d+PMhp3AgMBAAECgYBewVI9c46eOwa3Fikn/YgDDFoCINq7ivw0V6YfH+S4urh6janKXDIB4Lmtbepf/hcO95S6QPh0s6qd39WC8mO5hoRK3qvK0+MM+Ie17pp4c6VSUHNpDe0CXJIma+QqdDHuq3k9sk3Rtnq1MMfF5BoPX3wQzjbE9h9v67wbx2H1oQJBANed5ok39Y1A7LSubUICM2VgP+gT22rg1iwFD23H1qIABwys/pq6aHEmf80Oh7Y3UzOZviwcpDues9rhDqVMpgcCQQDNRMRglnYoO4qkmDHI3A3rUOREnEBrQ/QLgVbmIk5x2jA7x2jh9jesIRV5+xHCgA7rW4ff+udAUK1RkzEBZ0wRAkA6mtNvVoNqekwcLBDMUTbRBiE4njUUTrpHyrRP3XJMI//GhTrKqYH7x0ATZzCh6VW2/8G90aceAVvXUTae3T9/AkEAwoW6e7Xaf0H9nwFDnI88+ZUM3SAdxAj/iq+lRC2anTYho2TTtd743zvy+Ee/isyEVvHEj7Nb1o0d0kJknGnhoQJBAIW1gEN4VpndWVg0fFeKeY1WKuHZC6N70Tc7GEYMxAlWj5kRyn1JU4QjDn6hT5AY7HQUgqMmuOf+FfoAyfV6JQI=`;

const signature = sign(json, privateKey);
console.log("Signature:", signature);
